//
//  GroupModel.swift
//  LocationTrackerAdmin
//
//  Created by mac on 2025/2/25.
//

//
//  GroupModel.swift
//  LocationTrackerAdmin
//
//  Created by mac on 2025/2/25.
//

import Vapor
import Fluent
import SQLKit
final class GroupModel: Model, Content {
    static var schema: String {
        return "groups"
    }
    
    @ID(custom: FieldKeys.id)
    var id: String?
    
    @Field(key: FieldKeys.name)
    var name: String
    
    @Field(key: FieldKeys.creatorID)
    var creatorID: String
    
    @Field(key: FieldKeys.createDate)
    var createDate: Date
    
//    @Field(key: FieldKeys.memberCount)
//    var memberCount: Int
    
    @Children(for: \.$group)
    var members: [GroupMemberModel]
    
    init() { }
    
    init(id: String? = nil, name: String, creatorID: String, createDate: Date) {
        self.id = id
        self.name = name
        self.creatorID = creatorID
        self.createDate = createDate
    }
}

extension GroupModel {
    struct FieldKeys {
        static var id: FieldKey { "group_id" }
        static var name: FieldKey { "group_name" }
        static var creatorID: FieldKey { "group_creator_id" }
        static var createDate: FieldKey { "group_create_date" }
    }
}

struct GroupModelMigration: AsyncMigration {
    func prepare(on database: Database) async throws {
        try await database.schema(GroupModel.schema)
            .field(GroupModel.FieldKeys.id, .string, .required, .custom("COMMENT '群组ID'"))
            .field(GroupModel.FieldKeys.name, .string, .required, .custom("COMMENT '群组名称'"))
            .field(GroupModel.FieldKeys.creatorID, .string, .required, .custom("COMMENT '群组创建人ID'"))
            .field(GroupModel.FieldKeys.createDate, .custom("datetime(0)"), .required, .sql(.default(SQLFunction("now"))), .custom("COMMENT '群组创建日期'"))
            .create()
    }
    
    func revert(on database: Database) async throws {
        try await database.schema(GroupModel.schema).delete()
    }
}

